package org.example.security.auth.config.authorize.jwt;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@EnableAuthorizationServer
// @Configuration
public class AuthorizationServerConfigUseJwt extends AuthorizationServerConfigurerAdapter {

    @Resource
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthenticationManager authenticationManagerBean;

    @Resource
    private UserDetailsService userDetailsService;

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 配置签名使用的密钥，生产环境建议使用非对称加密
        jwtAccessTokenConverter.setSigningKey("123456");
        return jwtAccessTokenConverter;

    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        // 允许表单认证
        security.allowFormAuthenticationForClients();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        // 配置JWT的内容增强器，可以在payload中添加自定义数据
        List<TokenEnhancer> delegates = new LinkedList<>();
        delegates.add(new JwtTokenEnhancer());
        delegates.add(jwtAccessTokenConverter());

        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(delegates);

        // 密码模式需要配置
        endpoints.authenticationManager(authenticationManagerBean)
                // jwt token存储策略
                .tokenStore(tokenStore())
                // jwt token 转换器
                .accessTokenConverter(jwtAccessTokenConverter())
                // jwt token 增强器
                .tokenEnhancer(tokenEnhancerChain)
                .reuseRefreshTokens(false)
                .userDetailsService(userDetailsService)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        /*
            授权码模式： authorization_code
            1、应用：发起授权请求 浏览器点击跳转到 http://localhost:8080/oauth/authorize?client_id=client&redirect_uri=http://localhost:8081/login&response_type=code&state=YgmA8g
            2、用户：登陆授权中心
            3、用户：同意授权
            4、授权中心：通过redirect_uri回调应用，并带上code参数  http://www.baidu.com?code=qxVX0R
            5、应用：获取token  POST 'http://localhost:8080/oauth/token?grant_type=authorization_code&client_id=client&client_secret=123456&redirect_uri=http://www.baidu.com&scope=all&code=qxVX0R'
            6、应用：带上access_token从资源服务获取资源   http://localhost:8080/user/current?access_token=602b7c24-e104-461e-bc82-5ed742264c30


            简化模式：implicit
            1、应用：发起授权请求  http://localhost:8080/oauth/authorize?response_type=token&client_id=client&redirect_uri=http://www.baidu.com&scope=all
            2、用户：登陆授权中心
            3、用户：同意授权
            4、授权中心：通过redirect_uri回调应用，并带上access_token参数  https://www.baidu.com/#access_token=a2756e7a-78e9-4e50-8d79-37c3eb998b66&token_type=bearer&expires_in=3599
            5、应用：带上access_token从资源服务获取资源   http://localhost:8080/user/current?access_token=a2756e7a-78e9-4e50-8d79-37c3eb998b66


            客户端模式：client_credentials
            POST http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=client&client_secret=123456&scope=all


            密码模式：password
            http://localhost:8080/oauth/token?username=admin&password=admin&grant_type=password&client_id=client&client_secret=123456&scope=all


            刷新令牌：refresh_token
            http://localhost:8080/oauth/token?grant_type=refresh_token&client_id=client&client_secret=123456&refresh_token={refresh_token值}

         */

        // 以下配置，生产环境应该从数据库获取
        // clients.jdbc(datasource);
        // clients.withClientDetails(clientDetails());
        clients.inMemory()
                // 应用注册时生成的APP_ID
                .withClient("client")
                // 应用注册时生成的密码
                .secret(passwordEncoder.encode("123456"))
                // 应用注册时填写的回调地址
                .redirectUris("http://www.baidu.com")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(86400)
                .scopes("all")
                // .autoApprove(true)
                .authorizedGrantTypes("authorization_code", "implicit", "client_credentials", "password", "refresh_token");
    }

}
